﻿using Custom.Infrastructure;
using Custom.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Custom.Service.Repository
{
    public class SaleInfoRepository : DbContext<SaleInfo>
    {
        public List<SaleInfo> GetAllSaleInfos()
        {
            string sql = "select s.id, s.cusid, c.cusname, c.cardno, c.identityno, c.mobile, s.totalamount, s.createman, s.createtime " +
                "from saleinfo s left join custominfo c on s.cusid = c.id " +
                "order by s.createtime desc";

            return Db.Ado.SqlQuery<SaleInfo>(sql);
        }

        public void Insert(SaleInfo sale, List<SaleDetail> details)
        {
            Db.Ado.BeginTran();
            try
            {
                Insert(sale);

                foreach (SaleDetail d in details)
                {
                    string sql = "insert into saledetail(saleid, name, price, quantity, amount) values(@saleid, @name, @price, @quantity, @amount)";
                    Db.Ado.ExecuteCommand(sql, new
                    {
                        saleid = d.saleid,
                        name = d.name,
                        price = d.price,
                        quantity = d.quantity,
                        amount = d.amount
                    });
                }
                Db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        public void BatchDelete(List<long> ids)
        {
            Db.Ado.BeginTran();

            try
            {
                foreach (long id in ids)
                {
                    Db.Ado.ExecuteCommand("delete from saleinfo where id = @id", new { id = id });

                    Db.Ado.ExecuteCommand("delete from saledetail where saleid = @id", new { id = id });
                }
                Db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
            }
        }
    }
}
